# Kestrel: An XMPP-based Many-Task Computing Scheduler
# Author: Lance Stout <lancestout@gmail.com>
#
# Copyright 2009-2010 Clemson University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Modules provide a single aspect of functionality that can be turned
on or off depending on the state and needs of the application.
"""


class Module(object):
    """
    A module is a basic unit of functionality in the application.
    The intent is that modules can be started and stopped at any
    time while the application is running so that new functionality
    can be added or unneeded functions turned off.
    """

    def __init__(self, name):
        self.name = name
        self.kernel = None
        self.registered = False
        self.events = {'kernel/start': self.start,
                       'kernel/stop': self.stop}
        self.started = False

    def register(self, kernel):
        """
        Register the module's event handlers with the application
        kernel.
        """
        self.kernel = kernel
        for event in self.events:
            self.kernel.add_handler(event, self.events[event])
        self.registered = True

    def unregister(self):
        """
        Unregister the module's event handlers with the application
        kernel.
        """
        for event in self.events:
            self.kernel.del_handler(event, self.events[event])

    def start(self, *args):
        """
        Start the module and raise a start event.
        """
        if not self.started:
            self.started = True
            self.kernel.event('%s/start' % self.name)

    def stop(self, *args):
        """
        Stop the module and raise a stop event.
        """
        if self.started:
            self.started = False
            self.kernel.event('%s/stop' % self.name)
